package com.sinogrand.elevator.ui.screens

import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.WebChromeClient
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.zIndex
import com.sinogrand.elevator.utils.LogTags
import android.util.Log

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FileViewerScreen(
    fileUrl: String,
    fileName: String,
    onNavigateBack: () -> Unit
) {
    Log.i(LogTags.APPROVAL_SCREEN, "📱 FileViewerScreen 打开文件:")
    Log.i(LogTags.APPROVAL_SCREEN, "   📄 文件名: $fileName")
    Log.i(LogTags.APPROVAL_SCREEN, "   🔗 文件URL: $fileUrl")
    
    var pageTitle by remember { mutableStateOf(fileName) }
    var isLoading by remember { mutableStateOf(true) }
    var hasError by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf("") }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = pageTitle,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                    navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = paddingValues.calculateTopPadding())
        ) {
            AndroidView(
                factory = { context ->
                    WebView(context).apply {
                        layoutParams = android.view.ViewGroup.LayoutParams(
                            android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                            android.view.ViewGroup.LayoutParams.MATCH_PARENT
                        )
                        
                        settings.apply {
                            javaScriptEnabled = true
                            domStorageEnabled = true
                            loadWithOverviewMode = true
                            useWideViewPort = true
                            setSupportZoom(true)
                            builtInZoomControls = true
                            displayZoomControls = false
                            mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                            allowFileAccess = true
                            allowContentAccess = true
                            @Suppress("DEPRECATION")
                            allowFileAccessFromFileURLs = true
                            @Suppress("DEPRECATION")
                            allowUniversalAccessFromFileURLs = true
                            userAgentString = userAgentString + " ElevatorApp/1.0"
                            cacheMode = android.webkit.WebSettings.LOAD_DEFAULT
                            databaseEnabled = true
                        }

                        webViewClient = object : WebViewClient() {
                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun onPageFinished(view: WebView?, url: String?) {
                                super.onPageFinished(view, url)
                                Log.d(LogTags.APPROVAL_SCREEN, "✅ 文件页面加载完成: $url")
                                isLoading = false
                                hasError = false
                            }

                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
                                super.onPageStarted(view, url, favicon)
                                Log.d(LogTags.APPROVAL_SCREEN, "🔄 开始加载文件页面: $url")
                                isLoading = true
                                hasError = false
                            }

                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
                                super.onReceivedError(view, errorCode, description, failingUrl)
                                Log.e(LogTags.APPROVAL_SCREEN, "❌ 文件加载错误 - 错误码: $errorCode, 描述: $description, URL: $failingUrl")
                                isLoading = false
                                hasError = true
                                errorMessage = description ?: "加载失败"
                                pageTitle = "加载失败"
                            }

                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun onReceivedHttpError(view: WebView?, request: android.webkit.WebResourceRequest?, errorResponse: android.webkit.WebResourceResponse?) {
                                super.onReceivedHttpError(view, request, errorResponse)
                                Log.e(LogTags.APPROVAL_SCREEN, "❌ HTTP错误 - 状态码: ${errorResponse?.statusCode}, URL: ${request?.url}")
                            }

                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                                Log.d(LogTags.APPROVAL_SCREEN, "🔗 拦截URL加载: $url")
                                url?.let {
                                    view?.loadUrl(it)
                                }
                                return true
                            }
                        }

                        webChromeClient = object : WebChromeClient() {
                            override fun onReceivedTitle(view: WebView?, title: String?) {
                                super.onReceivedTitle(view, title)
                                Log.d(LogTags.APPROVAL_SCREEN, "📄 接收到文件页面标题: $title")
                                if (!title.isNullOrEmpty() && title != "about:blank") {
                                    pageTitle = title
                                }
                            }

                            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                                super.onProgressChanged(view, newProgress)
                                Log.d(LogTags.APPROVAL_SCREEN, "📊 文件页面加载进度: $newProgress%")
                            }
                        }

                        // 延迟加载URL，确保WebView完全初始化
                        post {
                            try {
                                if (fileUrl.isNotEmpty()) {
                                    loadUrl(fileUrl)
                                    Log.d(LogTags.APPROVAL_SCREEN, "🚀 开始加载文件URL: $fileUrl")
                                } else {
                                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 文件URL为空")
                                    hasError = true
                                    errorMessage = "文件URL为空"
                                    isLoading = false
                                }
                            } catch (e: Exception) {
                                Log.e(LogTags.APPROVAL_SCREEN, "❌ 加载文件失败: ${e.message}", e)
                                hasError = true
                                errorMessage = "加载文件失败: ${e.message}"
                                isLoading = false
                            }
                        }
                    }
                },
                modifier = Modifier.fillMaxSize(),
                update = { webView ->
                    webView.requestLayout()
                }
            )

            // 加载指示器
            if (isLoading) {
                Box(
                    modifier = Modifier
                        .matchParentSize()
                        .zIndex(1f),
                    contentAlignment = Alignment.Center
                ) {
                    Card(
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f)
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
                    ) {
                        Row(
                            modifier = Modifier.padding(16.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(24.dp),
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.width(12.dp))
                            Text(
                                text = "文件加载中...",
                                fontSize = 14.sp,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                        }
                    }
                }
            }

            // 错误显示
            if (hasError) {
                Box(
                    modifier = Modifier
                        .matchParentSize()
                        .zIndex(1f),
                    contentAlignment = Alignment.Center
                ) {
                    Card(
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f)
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
                    ) {
                        Column(
                            modifier = Modifier.padding(24.dp),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                text = "文件加载失败",
                                fontSize = 18.sp,
                                fontWeight = FontWeight.Bold,
                                color = MaterialTheme.colorScheme.error
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = errorMessage,
                                fontSize = 14.sp,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                            Spacer(modifier = Modifier.height(16.dp))
                            Button(
                                onClick = {
                                    // 重新加载
                                    isLoading = true
                                    hasError = false
                                    errorMessage = ""
                                }
                            ) {
                                Text("重试")
                            }
                        }
                    }
                }
            }
        }
    }
}
